package kamikaze.service.product;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.Query;

import kamikaze.entity.Product;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;

@ServiceConfig(path = "product.edit.action", method = HttpMethod.POST)
public class EditProductService implements Service {

	@Override
	public String serve(ServiceContext ctx) throws Exception {
		final String id = ctx.getRequest().getParameter("id");
		if (id != null && !id.isEmpty()) {
			
			
			Query q = ctx.getEntityManager()
					.createQuery("Select p from Product p where p.productId= :productId and deleted=false and ownerKey= :ownerKey");
			q.setParameter("productId", Long.valueOf(id));
			q.setParameter("ownerKey",ctx.getUserSession().asUser().getId());
			
			Product product = (Product) q.getSingleResult();
			product.setCategory(ctx.getRequest().getParameter("prodCat"));
			product.setName(ctx.getRequest().getParameter("prodName"));
			product.setPicture(ctx.getRequest()
					.getParameter("prodPicture"));

			BigDecimal price = BigDecimal.ZERO;
			String strPrice = ctx.getRequest().getParameter("prodPrice");
			if (strPrice != null) {
				strPrice = strPrice.replaceAll(",", "");
				Double dprice = Double
						.parseDouble(strPrice);
				price = BigDecimal.valueOf(dprice);
			}
			product.setPrice(price);
			product.setComment(ctx.getRequest()
					.getParameter("sellerComment"));

			List<String> errors = product.validate();
			if (!errors.isEmpty()) {
				throw new ServiceException(errors.toString());
			} else {
				ctx.getEntityManager().persist(product);
			}

			return "redirect:/service/product/list";
		} else {
			throw new ServiceException("Product ID is unknown");
		}
	}

}
